<template>
  <div style="background-color: white; width: 100%; height: 100%">
    <el-button
      link
      @click="router.push('/ProducManagement/PurchasingsQuery')"
      style="margin-left: 10px"
      >‹返回</el-button
    >
    &nbsp;
    <span>|</span>
    &nbsp;
    <span style="font-size: 17px; font-weight: 500; color: green"
      > 采购/委外订单头信息 </span
    >


    
    <hr style="background-color: #d3d3d3; height: 1px; border: none" />

    
  <el-tabs type="border-card" style="margin-top: 30px;margin-left: 30px;">
    <el-tab-pane label="标准信息" >  
      <el-form  class="demo-ruleForm" :model="form" ref="formRef" label-width="auto" style="max-width: 1100px;margin-left: 180px;margin-top: 30px;">
            <el-form-item label="订单编码" style="margin: 40px;width: 500px;"  prop="purchasingNo" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.purchasingNo" :readonly="true" />
            </el-form-item>

            <el-form-item label="订单名称" style="width: 500px;float: right;margin-top: -72px;" prop="purchasingName" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.purchasingName" />
            </el-form-item>

            <el-form-item label="订单类型" style="margin: 40px;width: 500px;" prop="purchasingTypeId" :rules="[ { required: true, message: '必填' },]" >
            <el-select v-model="form.purchasingTypeId" placeholder="请选择">
              
            <el-option v-for="item in options" :label="item.purchasingTypeName" :value="item.purchasingTypeId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="所属项目" style="width: 500px;float: right;margin-top: -72px;">
                <el-select v-model="form.projectId"  placeholder="请选择">
                    
                    <el-option v-for="item in options2" :label="item.projectName" :value="item.projectId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="订单备注" style="margin: 40px;width: 1060px;" >
                <el-input v-model="form.purchasingDesc" type="textarea" />
            </el-form-item>


            <el-form-item label="供应商" style="margin: 40px;width: 500px;" prop="suppliersId" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.suppliersId" placeholder="请选择">
                    
                    <el-option v-for="item in options1" :label="item.suppliersName" :value="item.suppliersId"/>
            </el-select>
            </el-form-item>

            <el-form-item label="订单金额（不含税）" style="width: 500px;float: right;margin-top: -72px;" >
                <el-input v-model="form.orderAmount" disabled/>
            </el-form-item>

            <el-form-item label="币种" style="margin: 40px;width: 500px;" prop="currency" :rules="[ { required: true, message: '必填' },]">
            <el-select v-model="form.currency" placeholder="请选择">
                <el-option label="人民币" value="人民币" />
                <el-option label="美元" value="美元" />
                <el-option label="欧元" value="欧元" />
                <el-option label="英镑" value="英镑" />
                <el-option label="日元" value="日元" />

            </el-select>
            </el-form-item>

            <el-form-item label="预收款金额" style="width: 500px;float: right;margin-top: -72px;" prop="advancePayment" :rules="[ { required: true, message: '必填' },]" >
                <el-input v-model="form.advancePayment" />
            </el-form-item>


            <el-form-item label="订单开始时间" style="margin: 40px;width: 500px;" >
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.startTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="订单结束时间" style="width: 500px;float: right;margin-top: -72px;" >
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.endTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="签订时间" style="margin: 40px;width: 500px;" prop="signUpTime" :rules="[ { required: true, message: '必填' },]">
                <el-col :span="11">
                    <el-date-picker
                    v-model="form.signUpTime"
                    type="date"
                    style="width: 365px"
                    />
                </el-col>
            </el-form-item>

            <el-form-item label="状态" style="width: 500px;float: right;margin-top: -72px;" prop="purchasingStatus" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.purchasingStatus"   >
                <el-option label="新建" :value="1" />
                <el-option label="确认" :value="2" />
            </el-select>
            </el-form-item>
            

            <el-form-item label="计税类型" style="margin: 40px;width: 500px;">
                <el-select v-model="form.taxType" >
                <el-option label="增值税" value="增值税" />
                <el-option label="附加税" value="附加税" />
            </el-select>
            </el-form-item>

            <el-form-item label="税率" style="width: 500px;float: right;margin-top: -72px;">
                <el-input v-model="form.taxRate" />
            </el-form-item>

            <el-form-item label="开票金额（含税）" style="margin: 40px;width: 500px;" disabled="true">
                <el-input v-model="form.billing" disabled/>
            </el-form-item>

            <el-form-item label="已收款金额（含税）" style="width: 500px;float: right;margin-top: -72px;">
                <el-input v-model="form.paidFor" disabled/>
            </el-form-item>

            <el-form-item label="制单人" style="margin: 40px;width: 500px;" prop="billMaking" :rules="[ { required: true, message: '必填' },]">
                <el-input v-model="form.billMaking" />
            </el-form-item>

            <el-form-item label="制单部门" style="width: 500px;float: right;margin-top: -72px;" prop="departmentId" :rules="[ { required: true, message: '必填' },]">
                <el-select v-model="form.departmentId" placeholder="请选择">
                    <el-option label="请选择" :value="0" />
                    <el-option v-for="item in options3" :label="item.departmentName" :value="item.departmentId"/>
            </el-select>
            </el-form-item>

            <el-button type="success" @click="AddPurchasings">保存</el-button>
          <el-button
                style=" width: 80px"
                v-show="isshow"
                @click="AddPurchasings()"
                >{{ tianjia }}</el-button
              >
            
        </el-form>
    </el-tab-pane>
    <el-tab-pane label="自定义">   <el-form  class="demo-ruleForm" :model="form" ref="formRef" label-width="auto" style="max-width:400px;margin-left: 180px;margin-top: 30px;">
    <el-form-item label="是否三方合同:" prop="contract" :rules="[ { required: true, message: '必填' },]">
      <el-select v-model="form.contract"  >
                <el-option label="是" value="是" />
                <el-option label="否" value="否" />
            </el-select>
    </el-form-item>
    <el-form-item label="付款条件:" prop="condition">
      <el-select v-model="form.condition" >
                <el-option label="2/10" value="2/10" />
                <el-option label="5/10" value="5/10" />
            </el-select>
    </el-form-item>
    <el-form-item label="销售人员:" prop="salesperson">
      <el-input v-model="form.salesperson" />
    </el-form-item>
    <el-form-item label="最晚付款日期:" prop="latestDate">
      <el-date-picker
        v-model="form.latestDate"
        type="date"
        placeholder="最晚付款日期"
        format="YYYY-MM-DD"
        value-format="YYYY-MM-DD"
      />
    </el-form-item>
    <el-form-item label=" test1:" prop="tests" :rules="[ { required: true, message: '必填' },]">
      <el-input v-model="form.tests" />
    </el-form-item>
    <!-- <el-form-item>
      <el-button type="success" @click="AddBusinessLicense()">
        保存
      </el-button>
    </el-form-item> -->
  </el-form>
</el-tab-pane>
  </el-tabs>
  
  <h2 style="font-size: 17px;font-weight: 500; color: #409EFF; margin-top: 60px; margin-left: 50px; margin-bottom: 10px;" >采购/委外订单行信息</h2>
        <hr style='background-color:#d3d3d3; height:1px; border:none;'>

    <el-tabs type="border-card" style="margin-top: 30px;margin-left: 30px">
      <!-- 订单行的信息 -->
      <el-tab-pane label="订单行">
        <div class="demo-collapse">
          <el-collapse accordion> </el-collapse>
        </div>
        <div style="background-color: white; width: 100%; height: 100%">
          <el-button
            type="info"
            style="float: right; margin-top: -10px; margin-right: 20px"
            @click="addOrderLine()"
            >+新增订单行</el-button
          >

          <div style="margin: 20px">
            <el-table  style="width: 100%">
              <el-table-column prop="orderLineId" label="行号" />
              <el-table-column prop="inventoryInfoId" label="物料编码" />
              <!-- <el-table-column prop="contactPersonsTell" label=" 物料名称" /> -->
              <el-table-column prop="orderLinePrice" label="单价（不含税）" width="180" />
              <el-table-column prop="orderLineNum" label="数量	" />
              <el-table-column prop="unit" label="单位" />
              <el-table-column prop="bankAmount" label=" 金额（不含税）" width="180"/>
              <el-table-column prop="lineSummary" label="	摘要" />
              <el-table-column prop="handleTime" label="创建时间" width="180">
                <template #default="{ row }">
                  {{ moment(row.handleTime).format("YYYY-MM-DD HH:mm:ss") }}
                </template>
              </el-table-column>
              <el-table-column prop="handle" label="创建人" width="180" />
            </el-table>
          </div>
        </div>

      </el-tab-pane>
      <!-- 付款计划行 -->
      <el-tab-pane label="付款计划行">
        <div style="background-color: white;width: 100%;height: 100%;">
   <el-button type="info" style="float: right;margin-top: -10px;margin-right: 20px;" @click="addPay">+新增付款计划</el-button>
   
   <div style="margin: 20px;">
     <el-table  style="width: 100%">
<el-table-column prop="paymentPlanId" label="行号" />
<el-table-column prop="paymentPlanDate" label="付款计划时间" width="180">
  <template #default="{row}">
   {{ moment(row.paymentPlanDate).format("YYYY-MM-DD") }}
 </template>
</el-table-column>
<el-table-column prop="proportionPayment" label=" 付款比例（%）" width="180"/>
<el-table-column prop="paymentPrice" label="付款金额（不含税）" width="180"/>
<el-table-column prop="paymentAdvance" label="预付款"/>
<el-table-column prop="0" label=" 开票金额（含税）" width="180"/>
<el-table-column prop="0" label="已付款金额（含税）" width="180"/>
<el-table-column prop="remarks" label="备注"/>
<el-table-column prop="handleTime" label="创建时间" width="180">
 <template #default="{row}">
   {{ moment(row.handleTime).format("YYYY-MM-DD HH:mm:ss") }}
 </template>
</el-table-column>
<el-table-column prop="handle" label="创建人" width="180" />
</el-table>

   </div>
 
 </div>

      </el-tab-pane>
    </el-tabs>
    
  </div>
</template>

<script lang="ts" setup>
import { ref, reactive, onMounted, readonly ,computed} from "vue";
import { ElMessage, ElMessageBox } from "element-plus";
import { useRouter, useRoute } from "vue-router";
import axios from "axios";
const formRef = ref<FormInstance>();
const apiurl = import.meta.env.VITE_APP_API_URL_ProductionAdd;
const apiurl1 = import.meta.env.VITE_APP_API_URL_ProductionShow;
const router = useRouter();
const route = useRoute();
import type { ComponentSize, FormInstance, FormRules } from "element-plus";
const dialogFormVisible = ref(false);
const dialogFormVisible2 = ref(false);
import moment from "moment";


//获取登录信息
const UserList = ref([]);
const LoadUserJSONData = () => {
  //读出数据
  const value = localStorage.getItem("userInfo");
  //反序列化JSON字符串
  UserList.value = JSON.parse(value);
  UserList.value.forEach((item: any) => {
    form.handle = item.userName;
  });
};




let totalSum= ref(0);
// 计算行金额的计算属性
const aa= computed(() => {

  
  return Number(ruleForm.orderLinePrice) * Number(ruleForm.orderLineNum);
 
});
const addOrderLine=()=>{
  return ElMessage.error('请保存过后添加')
}

const addPay=()=>{
  return ElMessage.error('请保存过后添加')
}
totalSum=aa
console.log(totalSum);
//物料下拉
const ItemInfoList: any = ref([]);
const getItemInfoList = () => {
  axios
    .post(apiurl1 + "/api/ShowProducManagement/ShowItemInfo", {})
    .then((res) => {
      console.log(res);
      ItemInfoList.value = res.data.data;
    })
    .catch((err) => {
      console.log(err);
    });
};

//订单类型
const options=ref([])
const OrderType=()=>{
    axios.post(apiurl1+'/api/ShowProducManagement/PurchasingTypeShow',{}).then((res)=>{
        options.value=res.data.data
    })
}

//供应商
const options1=ref([])
const SuppliersList=()=>{
    axios.post(apiurl1+'/api/ShowProducManagement/SupplierShow',{}).then((res)=>{
        options1.value=res.data.data
    })
}

//项目
const options2=ref([])
const Projects=()=>{
    axios.post(apiurl1+'/api/ShowProduction/GetProjectShow',{}).then((res)=>{
        options2.value=res.data.data
    })
}

//部门
const options3=ref([])
const Departments=()=>{
    axios.get(apiurl1+'/api/ShowProduction/GetDepartment').then((res)=>{
        options3.value=res.data.data
    })
}


//显示提交按钮
const isshow = ref(false);
//供应商编码是否只读
const isNo = ref(false);
const tianjia = ref("提交");

//点击保存进行下一步操作
const GetAdd = () => {
  
};


//供应商信息字段
const form = reactive({
  purchasinId: 0,
  purchasingNo: "",
  purchasingName: "",
  purchasingTypeId: "",
  projectId: "",
  purchasingDesc: "",
  suppliersId: "",
  orderAmount: 0,
  currency: "",
  advancePayment: "",
  startTime: "",
  endTime: "",
  signUpTime: "",
  purchasingStatus: "",
  taxType: "",
  taxRate: "",
  billing: 0,
  paidFor: 0,
  billMaking: "",
  departmentId: "",
  approvalStatus: 0,
  contract: "",
  condition: "",
  salesperson: "",
  latestDate:'',
  tests: "",
  handle: "张三",
  handleContext: "添加",
  pid: 0,
  isDelete: 0,
});

//采购/委外订单添加
const AddPurchasings = () => {
  if(form.contract==""){
    return ElMessage.error("请添加自定义信息")
  }
  isshow.value = true;
  isNo.value = true;
  const data={

    purchasingNo: form.purchasingNo,
    purchasingName: form.purchasingName,
    purchasingTypeId: form.purchasingTypeId,
    projectId: form.projectId,
    purchasingDesc: form.purchasingDesc,
    suppliersId: form.suppliersId,
    orderAmount: form.orderAmount,
    currency: form.currency,
    advancePayment: form.advancePayment,
    startTime: form.startTime,
    endTime: form.endTime,
    signUpTime: form.signUpTime,
    purchasingStatus: form.purchasingStatus,
    taxType: form.taxType,
    taxRate: form.taxRate,
    billing: form.billing,
    paidFor: form.paidFor,
    billMaking: form.billMaking,
    departmentId: form.departmentId,
    approvalStatus: form.approvalStatus,
    contract: form.contract,
    condition: form.condition,
    salesperson: form.salesperson,
    latestDate: form.latestDate,
    tests: form.tests,
    handle: form.handle,
    handleContext: form.handleContext,
    pid: form.pid,
    isDelete: 0,
    // orderLinesList:orderLinesList.value,
      // paymentPlansList: PaymentPlansAddList.value,
  }
  console.log(data);  
  axios
    .post(apiurl + "/api/ProducManagement/AddProcurement",data)
    .then((res) => {
      console.log(res.data);
      ElMessage.success("保存成功");
      router.push("/ProducManagement/PurchasingsQuery");
    })
    .catch((err) => {
      console.log(err);
      ElMessage.error("保存失败");

    });
};


//字段
interface RuleForm {
  purchasinId: number
  //订单行信息字段
  orderLineId: number;
  inventoryInfoId: string;
  orderLinePrice: string;
  position: string;
  orderLineNum: string;
  unit: string,
  bankAmount: number
  branchNo: string
  lineSummary: string

    //付款计划信息字段
    paymentPlanId: number;
    paymentPlanDate: string;
    proportionPayment: string;
    paymentPrice: string;
    paymentAdvance: string;
    remarks: string,
  
}

const formSize = ref<ComponentSize>("default");
const ruleFormRef = ref<FormInstance>();
const ruleForm = reactive<RuleForm>({
  purchasinId: 0,
  //订单行信息字段
  orderLineId: 0,
  inventoryInfoId: '',
  orderLinePrice: '',
  position: '',
  orderLineNum:'',
  unit: '',
  bankAmount: 0,
  branchNo: '',
  lineSummary: '',

    //付款计划信息字段
    paymentPlanId:0,
    paymentPlanDate: '',
    proportionPayment: '',
    paymentPrice:'',
    paymentAdvance:'',
    remarks: ''
});

//表单验证
const rules = reactive<FormRules<RuleForm>>({
  inventoryInfoId: [
    { required: true, message: "请选择", trigger: "blur" },
  ],
  orderLinePrice: [
    { required: true, message: "必填", trigger: "blur" },
  ],
  paymentPlanDate: [{ required: true, message: "必填", trigger: "blur" }],
  paymentPrice: [
    { required: true, message: '必填', trigger: 'blur' },
  ],
  proportionPayment: [
    { required: true, message: '必填', trigger: 'blur' },
  ],
  paymentAdvance: [
    { required: true, message: '必填', trigger: 'blur' },
  ]
});






//钩子函数
onMounted(() => {
  Projects()
  Departments()
  OrderType()
  SuppliersList()
  getItemInfoList()
  form.purchasingNo = new Date()
    .toString()
    .substring(7, 25)
    .replace(" ", "")
    .replace(" ", "")
    .replace(" ", "")
    .replace(":", "")
    .replace(":", "")+ Math.floor(Math.random() * 100);
    form.purchasingNo = form.purchasingNo.replace(" ", "");
    LoadUserJSONData()

});

</script>
